package com.aixin.csopuser.service;

import com.aixin.csopequity.domain.EquityLevelDef;
import com.aixin.csopequity.repository.EquityLevelRepository;
import com.aixin.csopsupplier.domain.ServiceDef;
import com.aixin.csopuser.domain.*;
import com.aixin.csopuser.model.CustomerModel;
import com.aixin.csopuser.repository.AxjyOrderDetailRepository;
import com.aixin.csopuser.repository.CustomerRepository;
import com.aixin.csopuser.repository.ServiceDefineRepository;
import com.aixin.csopuser.repository.YjkMembersRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.Predicate;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 云健康数据接口服务
 */
@Service
public class YjkApiService {

    @Autowired
    private YjkMembersRepository membersRepository;

    @Autowired
    private AxjyOrderDetailRepository orderDetailRepository;

    @Autowired
    private CustomerRepository customerRepository;

    @Autowired
    private ServiceDefineRepository serviceDefineRepository;

    @Autowired
    private EquityLevelRepository equityLevelRepository;

    public List<YjkMembers> findMembers( String mobilePhone) {
        // 最大返回100条
        PageRequest pr = PageRequest.of(0, 100);
        Page<YjkMembers> page = membersRepository.findAll(((root, query, cb) -> {
            List<Predicate> list = new ArrayList<>();

            if (!StringUtils.isEmpty(mobilePhone)) {
                list.add(cb.like(root.get("mobilePhone"), "%" + mobilePhone + "%"));
            }

            return query.where(list.toArray(new Predicate[list.size()]))
                    .getRestriction();
        }), pr);

        List<YjkMembers> list = page.getContent();
        for (YjkMembers members : list) {
            Set<YjkDmPackage> packages = members.getPackages();
            Set<YjkPackageItems> items = members.getPackageItems();

//            for (int i = items.size() - 1; i >= 0; i--) {
                items.removeIf(item -> !packages.stream()
                        .anyMatch(p -> p.getMemberId().equals(item.getMemberId()) && p.getMpId().equals(item.getMpId())));
//            }
        }
        return list;
    }

    public List<AxjyOrderDetail> getOrderDetail(String mobile) {
        return orderDetailRepository.findByMobile(mobile);
    }

    public List<CustomerDomain> apiGetCustomer(CustomerModel model) {

        // 组合查询条件，最大返回100条
        PageRequest pr = PageRequest.of(0, 100);
        Page<CustomerDomain> page = customerRepository.findAll(((root, query, cb) -> {
            List<Predicate> list = new ArrayList<>();

            if (!StringUtils.isEmpty(model.getCertType())) {
                list.add(cb.equal(root.get("certType"),  model.getCertType()));
            }
            if (!StringUtils.isEmpty(model.getCustName())) {
                list.add(cb.equal(root.get("custName"), model.getCustName()));
            }
            if (!StringUtils.isEmpty(model.getCertID())) {
                list.add(cb.equal(root.get("certID"),  model.getCertID()));
            }
            if (!StringUtils.isEmpty(model.getPhoneNumber())) {
                list.add(cb.equal(root.get("phoneNumber"),  model.getPhoneNumber()));
            }
            if (!StringUtils.isEmpty(model.getGender())) {
                list.add(cb.equal(root.get("gender"),  model.getGender()));
            }

            if (!StringUtils.isEmpty(model.getBirthday())) {

                Date startDate=null;
                Date endDate=null;
                try
                {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    startDate= sdf.parse(model.getBirthday());
                    Calendar calendar = new GregorianCalendar();
                    calendar.setTime(startDate);
                    calendar.add(calendar.DATE,1);
                    endDate=calendar.getTime();

                }
                catch (ParseException e)
                {
                    e.printStackTrace();
                }

                list.add(cb.greaterThanOrEqualTo(root.<Date>get("birthday"), startDate));
                list.add(cb.lessThanOrEqualTo(root.<Date>get("birthday"), endDate));
            }
            return query.where(list.toArray(new Predicate[list.size()]))
                    .getRestriction();
        }), pr);

        List<CustomerDomain> list = page.getContent();
        // 为每个用户权益查询其拥有的服务项
        list.forEach(customer -> {
            List<CustomerEquity> equities = new ArrayList<>(customer.getCustomerEquities());
            equities.forEach(customerEquity -> {
                List services = serviceDefineRepository.findEquityServices(customerEquity.getEquityID(), customerEquity.getCustLevelID());
                customerEquity.setServices(services);
            });
        });

        return page.getContent();
    }

    public List<EquityLevelDef> getAllEquityLevel() {
        return equityLevelRepository.getEquityLevel(null);
    }

    public List<ServiceDef> getAllService() {
        return serviceDefineRepository.findAllByServiceStatusLessThan(2);
    }
}
